package com.ruoyi.factorydata.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.factorydata.domain.*;
import com.ruoyi.factorydata.domain.dto.ModelInventoryPrintDTO;
import com.ruoyi.factorydata.domain.dto.ModelInventoryPrintDetailDTO;
import com.ruoyi.factorydata.mapper.ModelInventoryFlowMapper;
import com.ruoyi.factorydata.mapper.ModelInventoryMapper;
import com.ruoyi.factorydata.service.*;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysDictDataService;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 母版库存Service业务层处理
 *
 * @author ruoyi
 * @date 2025-07-27
 */
@Service
public class ModelInventoryServiceImpl extends ServiceImpl<ModelInventoryMapper, ModelInventory> implements IModelInventoryService {
    private final ModelInventoryMapper modelInventoryMapper;
    private final ModelInventoryFlowMapper modelInventoryFlowMapper;
    private final IWarehousePositionService warehousePositionService;
    private final IWarehouseInfoService warehouseInfoService;
    private final ICustomerDataService customerDataService;
    private final ISysDictDataService sysDictDataService;
    private final IPrintTemplateService printTemplateService;
    private final ISysConfigService sysConfigService;
    private final IWorkOrderInfoService workOrderInfoService;

    @Lazy
    public ModelInventoryServiceImpl(ModelInventoryMapper modelInventoryMapper,
                                     ModelInventoryFlowMapper modelInventoryFlowMapper,
                                     IWarehousePositionService warehousePositionService,
                                     IWarehouseInfoService warehouseInfoService,
                                     ICustomerDataService customerDataService,
                                     ISysDictDataService sysDictDataService,
                                     IPrintTemplateService printTemplateService,
                                     ISysConfigService sysConfigService,
                                     IWorkOrderInfoService workOrderInfoService) {
        this.modelInventoryMapper = modelInventoryMapper;
        this.modelInventoryFlowMapper = modelInventoryFlowMapper;
        this.warehousePositionService = warehousePositionService;
        this.warehouseInfoService = warehouseInfoService;
        this.customerDataService = customerDataService;
        this.sysDictDataService = sysDictDataService;
        this.printTemplateService = printTemplateService;
        this.sysConfigService = sysConfigService;
        this.workOrderInfoService = workOrderInfoService;
    }

    /**
     * 查询母版库存
     *
     * @param id 母版库存主键
     * @return 母版库存
     */
    @Override
    public ModelInventory selectModelInventoryById(Long id) {
        ModelInventory modelInventory = modelInventoryMapper.selectModelInventoryById(id);
        modelInventory.setWarehouseName(warehouseInfoService.getNameByIdAndCache(modelInventory.getWarehouseId(), new HashMap<>()));
        modelInventory.setWarehousePositionName(warehousePositionService.getByIdAndCache(modelInventory.getWarehousePositionId(), new HashMap<>()));
        return modelInventory;
    }

    @Override
    public ModelInventory getScannerInfo(Long inventoryId) {
        Assert.notNull(inventoryId, "参数不能为空");
        ModelInventory modelInventory = selectModelInventoryById(inventoryId);
        Assert.notNull(modelInventory, "数据不存在");
        //获取关联工单
        List<WorkOrderInfo> workOrderInfos = workOrderInfoService.selectWorkOrderInfoList(WorkOrderInfo.builder().modelMaterialCode(modelInventory.getModelNumber()).build());
        modelInventory.setWorkOrderInfoList(workOrderInfos);
        return modelInventory;
    }

    /**
     * 查询母版库存列表
     *
     * @param modelInventory 母版库存
     * @return 母版库存
     */
    @Override
    public List<ModelInventory> selectModelInventoryList(ModelInventory modelInventory) {
        List<ModelInventory> modelInventories = modelInventoryMapper.selectModelInventoryList(modelInventory);
        HashMap<Long, String> positionNameCache = new HashMap<>();
        HashMap<Long, String> warehouseNameCache = new HashMap<>();
        HashMap<Long, String> customNameCache = new HashMap<>();

        modelInventories.forEach(inventory -> {
            String positionName = warehousePositionService.getByIdAndCache(inventory.getWarehousePositionId(), positionNameCache);
            String warehouseName = warehouseInfoService.getNameByIdAndCache(inventory.getWarehouseId(), warehouseNameCache);
            String customerCode = customerDataService.getCodeByIdAndCache(inventory.getCustomerId(), customNameCache);
            ModelInventoryFlow lastFlow =modelInventoryFlowMapper.getLastFlow(inventory.getBatchNumber(),inventory.getModelNumber());
            inventory.setWarehousePositionName(positionName);
            inventory.setWarehouseName(warehouseName);
            inventory.setCustomerCode(customerCode);
            inventory.setRemark(Optional.ofNullable(lastFlow).map(ModelInventoryFlow::getRemark).orElse(null));
        });
        return modelInventories;
    }

    @Override
    public ModelInventoryPrintDTO printList(ModelInventory modelInventory) {
        Assert.notNull(modelInventory, "参数不能为空");
        Assert.notNull(modelInventory.getIdList(), "参数不能为空");

        String modelPrintDetailUrl = sysConfigService.selectConfigByKey("modelPrintDetailUrl");
        Assert.notNull(modelPrintDetailUrl, "母版详情未配置");
        HashMap<Long, String> customNameCache = new HashMap<>();

        List<ModelInventoryPrintDetailDTO> printDetailDTOList = modelInventoryMapper.selectModelInventoryList(modelInventory)
                .stream()
                .map(inventory -> {
                    String customerName = customerDataService.getCodeByIdAndCache(inventory.getCustomerId(), customNameCache);
                    String modelLevelOption = sysDictDataService.selectDictLabel("model_level_option", inventory.getModelLevel());
                    return ModelInventoryPrintDetailDTO.builder()
                            .qrCode(modelPrintDetailUrl+"?inventoryId=" + inventory.getId())
                            .customId(StringUtils.isNotBlank(customerName)?customerName:"自有")
                            .modelNum(inventory.getModelNumber())
                            .productionDate(DateFormatUtils.format(inventory.getProductionDate(), "yyyy/MM/dd"))
                            .modelMaterial(inventory.getModelMaterial())
                            .modelLevel(modelLevelOption)
                            .warehousePosition(inventory.getWarehousePositionCode())
                            .build();
                })
                .collect(Collectors.toList());
        PrintTemplate printTemplate = printTemplateService
                .lambdaQuery()
                .eq(PrintTemplate::getPrintType, "modelInfo")
                .orderByDesc(PrintTemplate::getId)
                .last(" limit 1")
                .one();
        Assert.notNull(printTemplate, "打印模板不存在");
        return ModelInventoryPrintDTO.builder()
                .templateName(printTemplate.getPrintType())
                .template(printTemplate.getContent())
                .detailList(printDetailDTOList)
                .build();
    }

    /**
     * 新增母版库存
     *
     * @param modelInventory 母版库存
     * @return 结果
     */
    @Override
    public int insertModelInventory(ModelInventory modelInventory) {
        modelInventory.setCreateTime(DateUtils.getNowDate());
        return modelInventoryMapper.insertModelInventory(modelInventory);
    }

    /**
     * 修改母版库存
     *
     * @param modelInventory 母版库存
     * @return 结果
     */
    @Override
    public int updateModelInventory(ModelInventory modelInventory) {
        modelInventory.setUpdateTime(DateUtils.getNowDate());
        return modelInventoryMapper.updateModelInventory(modelInventory);
    }

    /**
     * 批量删除母版库存
     *
     * @param ids 需要删除的母版库存主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteModelInventoryByIds(Long[] ids) {
        for (Long id : ids) {
            int update = deleteModelInventoryById(id);
            Assert.isTrue(update > 0, "报废失败");
        }
        return 1;
    }

    /**
     * 删除母版库存信息
     *
     * @param id 母版库存主键
     * @return 结果
     */
    @Override
    public int deleteModelInventoryById(Long id) {
        Assert.notNull(id, "参数不能为空");
        ModelInventory inventory = getById(id);
        Assert.notNull(inventory, "序号:" + id + "不存在");

        inventory.setUpdateBy(SecurityUtils.getUserId() + "");
        inventory.setUpdateTime(DateUtils.getNowDate());
        inventory.setStatus(0);
        return modelInventoryMapper.updateModelInventory(inventory);
    }

    @Override
    public void saveInventoryIn(InventoryReceiptInfo inventoryReceiptInfo, InventoryReceiptModelDetail inventoryReceiptModelDetail, String batchNumber) {
        ModelInventory modelInventory = ModelInventory.builder()
                .batchNumber(batchNumber)
                .warehouseId(inventoryReceiptModelDetail.getWarehouseId())
                .warehouseCode(inventoryReceiptModelDetail.getWarehouseCode())
                .warehousePositionId(inventoryReceiptModelDetail.getWarehousePositionId())
                .warehousePositionCode(inventoryReceiptModelDetail.getWarehousePositionCode())
                .customerId(inventoryReceiptInfo.getCustomerId())
                .modelSource(inventoryReceiptModelDetail.getModelSource())
                .modelNumber(inventoryReceiptModelDetail.getModelNumber())
                .productionDate(inventoryReceiptModelDetail.getProductionDate())
                .modelImages(inventoryReceiptModelDetail.getModelImages())
                .characterizationImages(inventoryReceiptModelDetail.getCharacterizationImages())
                .structureType(inventoryReceiptModelDetail.getStructureType())
                .structureParameters(inventoryReceiptModelDetail.getStructureParameters())
                .modelMaterial(inventoryReceiptModelDetail.getModelMaterial())
                .modelThickness(inventoryReceiptModelDetail.getModelThickness())
                .modelSize(inventoryReceiptModelDetail.getModelSize())
                .isAntiStick(inventoryReceiptModelDetail.getIsAntiStick())
                .antiStickType(inventoryReceiptModelDetail.getAntiStickType())
                .antiStickDuration(inventoryReceiptModelDetail.getAntiStickDuration())
                .isSampleRetained(inventoryReceiptModelDetail.getIsSampleRetained())
                .modelLevel(inventoryReceiptModelDetail.getModelLevel())
                .stockQuantity(inventoryReceiptModelDetail.getActualQuantity())
                .receiptDate(inventoryReceiptInfo.getReceiptDate())
                .status(1)
                .build();
        modelInventory.setCreateBy(inventoryReceiptInfo.getCreateBy());
        int insert = modelInventoryMapper.insertModelInventory(modelInventory);
        Assert.isTrue(insert > 0, "入库失败");
        //添加入库单明细
        ModelInventoryFlow inventoryFlow = ModelInventoryFlow.builder()
                .documentNumber(inventoryReceiptInfo.getReceiptType() == 2 ? inventoryReceiptInfo.getReceiptNumber() : inventoryReceiptInfo.getWorkOrderCode())
                .flowType("in")//入库单入库
                .documentType(inventoryReceiptInfo.getReceiptType() == 2 ? "modelIn" : "product_model")
                .warehouseId(inventoryReceiptModelDetail.getWarehouseId())
                .warehouseCode(inventoryReceiptModelDetail.getWarehouseCode())
                .warehousePositionId(inventoryReceiptModelDetail.getWarehousePositionId())
                .warehousePositionCode(inventoryReceiptModelDetail.getWarehousePositionCode())
                .modelSource(inventoryReceiptModelDetail.getModelSource())
                .modelNumber(inventoryReceiptModelDetail.getModelNumber())
                .productionDate(inventoryReceiptModelDetail.getProductionDate())
                .modelImages(inventoryReceiptModelDetail.getModelImages())
                .structureType(inventoryReceiptModelDetail.getStructureType())
                .structureParameters(inventoryReceiptModelDetail.getStructureParameters())
                .modelMaterial(inventoryReceiptModelDetail.getModelMaterial())
                .modelThickness(inventoryReceiptModelDetail.getModelThickness())
                .modelSize(inventoryReceiptModelDetail.getModelSize())
                .isAntiStick(inventoryReceiptModelDetail.getIsAntiStick())
                .antiStickType(inventoryReceiptModelDetail.getAntiStickType())
                .antiStickDuration(inventoryReceiptModelDetail.getAntiStickDuration())
                .isSampleRetained(inventoryReceiptModelDetail.getIsSampleRetained())
                .modelLevel(inventoryReceiptModelDetail.getModelLevel())
                .quantity(inventoryReceiptModelDetail.getActualQuantity())
                .batchNumber(batchNumber)
                .bizTime(inventoryReceiptInfo.getReceiptDate())
                .build();
        inventoryFlow.setCreateBy(inventoryReceiptInfo.getCreateBy());
        inventoryFlow.setRemark(inventoryReceiptInfo.getRemark());
        insert = modelInventoryFlowMapper.insertModelInventoryFlow(inventoryFlow);
        Assert.isTrue(insert > 0, "入库失败");
    }

    @Override
    public void updateInventoryIn(Long inventoryId, InventoryReceiptInfo inventoryReceiptInfo, InventoryReceiptModelDetail inventoryReceiptModelDetail) {
        ModelInventory modelInventory = modelInventoryMapper.selectModelInventoryById(inventoryId);
        Assert.notNull(modelInventory, "母版库存不存在");
        ModelInventory updateModelInventory = ModelInventory.builder()
                .id(inventoryId)
                .batchNumber(modelInventory.getBatchNumber())
                .warehouseId(inventoryReceiptModelDetail.getWarehouseId())
                .warehouseCode(inventoryReceiptModelDetail.getWarehouseCode())
                .warehousePositionId(inventoryReceiptModelDetail.getWarehousePositionId())
                .warehousePositionCode(inventoryReceiptModelDetail.getWarehousePositionCode())

                .modelSource(inventoryReceiptModelDetail.getModelSource())
                .modelNumber(inventoryReceiptModelDetail.getModelNumber())
                .productionDate(inventoryReceiptModelDetail.getProductionDate())
                .modelImages(inventoryReceiptModelDetail.getModelImages())
                .characterizationImages(inventoryReceiptModelDetail.getCharacterizationImages())
                .structureType(inventoryReceiptModelDetail.getStructureType())
                .structureParameters(inventoryReceiptModelDetail.getStructureParameters())
                .modelMaterial(inventoryReceiptModelDetail.getModelMaterial())
                .modelThickness(inventoryReceiptModelDetail.getModelThickness())
                .modelSize(inventoryReceiptModelDetail.getModelSize())
                .isAntiStick(inventoryReceiptModelDetail.getIsAntiStick())
                .antiStickType(inventoryReceiptModelDetail.getAntiStickType())
                .antiStickDuration(inventoryReceiptModelDetail.getAntiStickDuration())
                .isSampleRetained(inventoryReceiptModelDetail.getIsSampleRetained())
                .modelLevel(inventoryReceiptModelDetail.getModelLevel())
                .stockQuantity(inventoryReceiptModelDetail.getActualQuantity())
                .receiptDate(inventoryReceiptInfo.getReceiptDate())
                .status(1)
                .build();
        updateModelInventory.setUpdateBy(inventoryReceiptInfo.getCreateBy());
        int update = modelInventoryMapper.updateModelInventory(updateModelInventory);
        Assert.isTrue(update > 0, "入库失败");
        //添加入库单明细
        ModelInventoryFlow inventoryFlow = ModelInventoryFlow.builder()
                .documentNumber(inventoryReceiptInfo.getWorkOrderCode())
                .flowType("in")//入库单入库
                .documentType("model_process_again")
                .warehouseId(inventoryReceiptModelDetail.getWarehouseId())
                .warehouseCode(inventoryReceiptModelDetail.getWarehouseCode())
                .warehousePositionId(inventoryReceiptModelDetail.getWarehousePositionId())
                .warehousePositionCode(inventoryReceiptModelDetail.getWarehousePositionCode())
                .modelSource(inventoryReceiptModelDetail.getModelSource())
                .modelNumber(inventoryReceiptModelDetail.getModelNumber())
                .productionDate(inventoryReceiptModelDetail.getProductionDate())
                .modelImages(inventoryReceiptModelDetail.getModelImages())
                .structureType(inventoryReceiptModelDetail.getStructureType())
                .structureParameters(inventoryReceiptModelDetail.getStructureParameters())
                .modelMaterial(inventoryReceiptModelDetail.getModelMaterial())
                .modelThickness(inventoryReceiptModelDetail.getModelThickness())
                .modelSize(inventoryReceiptModelDetail.getModelSize())
                .isAntiStick(inventoryReceiptModelDetail.getIsAntiStick())
                .antiStickType(inventoryReceiptModelDetail.getAntiStickType())
                .antiStickDuration(inventoryReceiptModelDetail.getAntiStickDuration())
                .isSampleRetained(inventoryReceiptModelDetail.getIsSampleRetained())
                .modelLevel(inventoryReceiptModelDetail.getModelLevel())
                .quantity(inventoryReceiptModelDetail.getActualQuantity())
                .batchNumber(modelInventory.getBatchNumber())
                .bizTime(inventoryReceiptInfo.getReceiptDate())
                .build();
        inventoryFlow.setCreateBy(inventoryReceiptInfo.getCreateBy());
        inventoryFlow.setRemark(inventoryReceiptInfo.getRemark());
        int insert = modelInventoryFlowMapper.insertModelInventoryFlow(inventoryFlow);
        Assert.isTrue(insert > 0, "入库失败");
    }

    @Override
    public Long countModelInventoryList(ModelInventory modelInventory) {
        return modelInventoryMapper.countModelInventoryList(modelInventory);
    }

    @Override
    public List<ModelInventory> selectModelCodeList(ModelInventory modelInventory) {
        return modelInventoryMapper.selectModelCodeList(modelInventory);
    }

    @Override
    public void saveInventoryOut(MaterialRequisitionDetail materialRequisitionDetail, String inventoryBatchNumber, BigDecimal inventoryQuantity) {
        ModelInventory inventory = lambdaQuery()
                .eq(ModelInventory::getBatchNumber, inventoryBatchNumber)
                .eq(ModelInventory::getModelNumber, materialRequisitionDetail.getModelNumber())
                .last("limit 1")
                .one();
        Assert.notNull(inventory, "批次:" + inventoryBatchNumber + "不存在");
        Assert.isTrue(new BigDecimal(inventory.getStockQuantity()).compareTo(inventoryQuantity) >= 0, "库存数量不足");
        inventory.setUpdateBy(SecurityUtils.getUserId() + "");
        inventory.setUpdateTime(DateUtils.getNowDate());
        inventory.setStockQuantity(inventory.getStockQuantity() - inventoryQuantity.intValue());
        inventory.setStatus(2);
        int update = modelInventoryMapper.updateModelInventory(inventory);
        Assert.isTrue(update > 0, "出库失败");
        //添加入库单明细
        ModelInventoryFlow inventoryFlow = ModelInventoryFlow.builder()
                .documentNumber(materialRequisitionDetail.getRequisitionNo())
                .flowType("out")//领料单出库
                .documentType("requisitionOut")
                .warehouseId(inventory.getWarehouseId())
                .warehouseCode(inventory.getWarehouseCode())
                .warehousePositionId(inventory.getWarehousePositionId())
                .warehousePositionCode(inventory.getWarehousePositionCode())
                .modelSource(inventory.getModelSource())
                .modelNumber(inventory.getModelNumber())
                .productionDate(inventory.getProductionDate())
                .modelImages(inventory.getModelImages())
                .structureType(inventory.getStructureType())
                .structureParameters(inventory.getStructureParameters())
                .modelMaterial(inventory.getModelMaterial())
                .modelThickness(inventory.getModelThickness())
                .modelSize(inventory.getModelSize())
                .isAntiStick(inventory.getIsAntiStick())
                .antiStickType(inventory.getAntiStickType())
                .antiStickDuration(inventory.getAntiStickDuration())
                .isSampleRetained(inventory.getIsSampleRetained())
                .quantity(inventoryQuantity.longValue())
                .batchNumber(inventoryBatchNumber)
                .bizTime(DateUtils.getNowDate())
                .build();
        inventoryFlow.setCreateBy(SecurityUtils.getUserId() + "");
        inventoryFlow.setRemark(materialRequisitionDetail.getRemark());
        int insert = modelInventoryFlowMapper.insertModelInventoryFlow(inventoryFlow);
        Assert.isTrue(insert > 0, "出库流水记录失败");
    }

    @Override
    public void saveInventoryIn(MaterialRequisitionDetail materialRequisitionDetail, String inventoryBatchNumber, BigDecimal inventoryQuantity) {
        ModelInventory inventory = lambdaQuery()
                .eq(ModelInventory::getBatchNumber, inventoryBatchNumber)
                .eq(ModelInventory::getModelNumber, materialRequisitionDetail.getModelNumber())
                .last("limit 1")
                .one();
        Assert.notNull(inventory, "批次:" + inventoryBatchNumber + "不存在");
        inventory.setUpdateBy(SecurityUtils.getUserId() + "");
        inventory.setUpdateTime(DateUtils.getNowDate());
        inventory.setStatus(1);
        inventory.setStockQuantity(inventory.getStockQuantity() + inventoryQuantity.intValue());
        int update = modelInventoryMapper.updateModelInventory(inventory);
        Assert.isTrue(update > 0, "出库失败");
        //添加入库单明细
        ModelInventoryFlow inventoryFlow = ModelInventoryFlow.builder()
                .documentNumber(materialRequisitionDetail.getRequisitionNo())
                .flowType("in")//领料单退料入库库
                .documentType("requisition_return_in")
                .warehouseId(inventory.getWarehouseId())
                .warehouseCode(inventory.getWarehouseCode())
                .warehousePositionId(inventory.getWarehousePositionId())
                .warehousePositionCode(inventory.getWarehousePositionCode())
                .modelSource(inventory.getModelSource())
                .modelNumber(inventory.getModelNumber())
                .productionDate(inventory.getProductionDate())
                .modelImages(inventory.getModelImages())
                .structureType(inventory.getStructureType())
                .structureParameters(inventory.getStructureParameters())
                .modelMaterial(inventory.getModelMaterial())
                .modelThickness(inventory.getModelThickness())
                .modelSize(inventory.getModelSize())
                .isAntiStick(inventory.getIsAntiStick())
                .antiStickType(inventory.getAntiStickType())
                .antiStickDuration(inventory.getAntiStickDuration())
                .isSampleRetained(inventory.getIsSampleRetained())
                .quantity(inventoryQuantity.longValue())
                .batchNumber(inventoryBatchNumber)
                .bizTime(DateUtils.getNowDate())
                .build();
        inventoryFlow.setCreateBy(SecurityUtils.getUserId() + "");
        inventoryFlow.setRemark(materialRequisitionDetail.getRemark());
        int insert = modelInventoryFlowMapper.insertModelInventoryFlow(inventoryFlow);
        Assert.isTrue(insert > 0, "出库流水记录失败");
    }

    @Override
    @Transactional
    public int outModelInventory(ModelInventory modelInventory) {
        ModelInventory inventory = getById(modelInventory.getId());
        Assert.notNull(inventory, "批次:" + modelInventory.getBatchNumber() + "不存在");
        Assert.isTrue(inventory.getStockQuantity() - modelInventory.getOutQuantity() >= 0, "库存数量不足");

        inventory.setUpdateBy(SecurityUtils.getUserId() + "");
        inventory.setUpdateTime(DateUtils.getNowDate());
        inventory.setStockQuantity(inventory.getStockQuantity() - modelInventory.getOutQuantity());
        if (StringUtils.equals(modelInventory.getOutReason(), "scrap_out")) {
            inventory.setStatus(-1);
        } else {
            inventory.setStatus(2);
        }
        int update = modelInventoryMapper.updateModelInventory(inventory);
        if (update > 0) {
            ModelInventoryFlow inventoryFlow = ModelInventoryFlow.builder()
                    .documentNumber(null)
                    .flowType("out")//领料单出库
                    .documentType(modelInventory.getOutReason())
                    .warehouseId(inventory.getWarehouseId())
                    .warehouseCode(inventory.getWarehouseCode())
                    .warehousePositionId(inventory.getWarehousePositionId())
                    .warehousePositionCode(inventory.getWarehousePositionCode())
                    .modelSource(inventory.getModelSource())
                    .modelNumber(inventory.getModelNumber())
                    .productionDate(inventory.getProductionDate())
                    .modelImages(inventory.getModelImages())
                    .structureType(inventory.getStructureType())
                    .structureParameters(inventory.getStructureParameters())
                    .modelMaterial(inventory.getModelMaterial())
                    .modelThickness(inventory.getModelThickness())
                    .modelSize(inventory.getModelSize())
                    .isAntiStick(inventory.getIsAntiStick())
                    .antiStickType(inventory.getAntiStickType())
                    .antiStickDuration(inventory.getAntiStickDuration())
                    .isSampleRetained(inventory.getIsSampleRetained())
                    .quantity(modelInventory.getOutQuantity())
                    .batchNumber(inventory.getBatchNumber())
                    .bizTime(DateUtils.parse(modelInventory.getOutTime(), "yyyy-MM-dd"))
                    .build();
            inventoryFlow.setCreateBy(SecurityUtils.getUserId() + "");
            inventoryFlow.setRemark(modelInventory.getRemark());
            int insert = modelInventoryFlowMapper.insertModelInventoryFlow(inventoryFlow);
            Assert.isTrue(insert > 0, "出库流水记录失败");
        }
        return update;
    }

    @Override
    public int revertInModelInventory(ModelInventory modelInventory) {
        ModelInventory inventory = getById(modelInventory.getId());
        Assert.notNull(inventory, "批次:" + modelInventory.getBatchNumber() + "不存在");

        inventory.setUpdateBy(SecurityUtils.getUserId() + "");
        inventory.setUpdateTime(DateUtils.getNowDate());
        inventory.setStockQuantity(inventory.getStockQuantity()+ modelInventory.getInQuantity());
        if(modelInventory.getInTime()!=null){
            inventory.setReceiptDate(DateUtils.parse(modelInventory.getInTime(), "yyyy-MM-dd"));
        }
        inventory.setStatus(1);
        int update = modelInventoryMapper.updateModelInventory(inventory);
        if (update > 0) {
            ModelInventoryFlow inventoryFlow = ModelInventoryFlow.builder()
                    .documentNumber(null)
                    .flowType("in")//领料单出库
                    .documentType(modelInventory.getInReason())
                    .warehouseId(inventory.getWarehouseId())
                    .warehouseCode(inventory.getWarehouseCode())
                    .warehousePositionId(inventory.getWarehousePositionId())
                    .warehousePositionCode(inventory.getWarehousePositionCode())
                    .modelSource(inventory.getModelSource())
                    .modelNumber(inventory.getModelNumber())
                    .productionDate(inventory.getProductionDate())
                    .modelImages(inventory.getModelImages())
                    .structureType(inventory.getStructureType())
                    .structureParameters(inventory.getStructureParameters())
                    .modelMaterial(inventory.getModelMaterial())
                    .modelThickness(inventory.getModelThickness())
                    .modelSize(inventory.getModelSize())
                    .isAntiStick(inventory.getIsAntiStick())
                    .antiStickType(inventory.getAntiStickType())
                    .antiStickDuration(inventory.getAntiStickDuration())
                    .isSampleRetained(inventory.getIsSampleRetained())
                    .quantity(modelInventory.getOutQuantity())
                    .batchNumber(inventory.getBatchNumber())
                    .bizTime(DateUtils.parse(modelInventory.getInTime(), "yyyy-MM-dd"))
                    .build();
            inventoryFlow.setCreateBy(SecurityUtils.getUserId() + "");
            inventoryFlow.setRemark(modelInventory.getRemark());
            int insert = modelInventoryFlowMapper.insertModelInventoryFlow(inventoryFlow);
            Assert.isTrue(insert > 0, "出库流水记录失败");
        }
        return update;
    }
}